package com.zygh.dlqwservice.module.controller.app;

import cn.hutool.core.date.DateUtil;
import com.zygh.dlqwservice.common.domain.ResultBeans;
import com.zygh.dlqwservice.common.domain.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Random;

/**
 * @author lee
 */
@RequestMapping("/upload")
@RestController
@Api(tags = "上传接口")
public class UploadController {
    @Value("${file.upload}")
    private String uploadDir;
    @PostMapping("/img")
    @ApiOperation("上传图片")
    public ResultBeans uploadImg(MultipartFile file) throws IOException {
        Random random = new Random();
        int num = random.nextInt(10000);
        //要保存的路径
        String savePath = File.separator+DateUtil.today() + File.separator + num + file.getOriginalFilename();
        //文件存在的目录
        String path = uploadDir+ File.separator+savePath;
        //是否能创建目录
        boolean make = false;
        File newFile = new File(path);
        //如果目录不存在，才创建
        if(!newFile.exists()){
            make  = newFile.mkdirs();
        }
        //创建失败目录
        if(!make){
            return ResultUtils.resultBeansError("创建目录失败");
        }
        //存储文件
        file.transferTo(newFile);
        //返回文件路径
        return ResultUtils.resultBeansSuccess( savePath);
    }
}
